#include "../include/head.h"

int add_user(MYSQL *mysql, char *username, char *salt, char *encrypted_password){
    char command[1024] = {0};
    sprintf(command,"insert into user (username,salt,encrypted_password) values ('%s','%s','%s');",username,salt,encrypted_password);
    int res = mysql_query(mysql,command);
    if(res != 0){
        fprintf(stderr, "%s:%s\n", "mysql_query_add_user 1", mysql_error(mysql));
        return -1;
    }
    bzero(command,sizeof(command));
    sprintf(command,"select user_id from user where username = '%s' and is_cancelled = 0;",username);
    res = mysql_query(mysql,command);
    if(res != 0){
        fprintf(stderr, "%s:%s\n", "mysql_query_add_user 2", mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    int user_id = atoi(row[0]);
    mysql_free_result(result);
    char filename[256] = {0};
    strcpy(filename,"/");
    strcat(filename,username);
    // 初始化用户根目录
    sprintf(command,"insert into file (filename,user_id,file_path,file_type) values ('%s','%d','%s','%c');",filename,user_id,filename,'d');
    res = mysql_query(mysql,command);
    if(res != 0){
        fprintf(stderr, "%s:%s\n", "mysql_query_add_file 3", mysql_error(mysql));
        return -1;
    }
    return 0;
}

int getInfo_user(MYSQL *mysql, char *username, char *salt, char *encrypted_password){
    char command[1024] = {0};
    printf("username:%s\n", username);
    sprintf(command,"select salt,encrypted_password from user where username = '%s' and is_cancelled = 0;",username);
    int ret = mysql_query(mysql,command);
    printf("command:%s\n", command);
    if(ret != 0){
        fprintf(stderr, "%s:%s\n", "mysql_query_getInfo_user", mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *res = mysql_store_result(mysql);
    if (res == NULL || mysql_num_rows(res) == 0) {
        printf("result null\n");
        return -1;
    } 

    MYSQL_ROW row = mysql_fetch_row(res);
    strcpy(salt,row[0]);
    printf("盐值%s\n", row[0]);
    strcpy(encrypted_password,row[1]);
    printf("密码%s\n", row[1]);
    return 1;
}

int cancel_user(MYSQL *mysql, char *username){
    char command[1024] = {0};
    sprintf(command,"update user set is_cancelled = 1 where username = '%s' and is_cancelled = 0;",username);
    int ret = mysql_query(mysql,command);
    if(ret != 0){
        fprintf(stderr, "%s:%s\n", "mysql_query_cancel_user", mysql_error(mysql));
        return -1;
    }
    return 0; 
}
